package cn.mugutu.finance.controller;

import cn.mugutu.finance.annotation.NoAuthenticationAPI;
import cn.mugutu.finance.dto.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@Controller
public class IndexController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

    @RequestMapping(value = {"/index", "/home", "/"})
    public String index() {
        return "index";
    }

    @RequestMapping("/welcome")
    public String welcom() {
        return "welcome";
    }

    //session超时后的中转跳转(跳出父框架到用户登录页面)
    @RequestMapping("/noSessionUI")
    @NoAuthenticationAPI
    public String noSession() {
        return "noSession";
    }

    //生成登陆验证码
    @RequestMapping("/validatecode")
    @NoAuthenticationAPI
    public void getValidatecode(HttpServletResponse response, HttpSession session) throws IOException {
        int width = 60;
        int height = 32;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        String capstr = hash1.substring(0, 4);
        session.setAttribute("validateCode", capstr);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(capstr, 1, 24);
        g.dispose();
        response.setContentType("image/jpeg");
        OutputStream strm = response.getOutputStream();
        ImageIO.write(image, "jpeg", strm);
        strm.close();
        LOGGER.info("用户登陆时刷新验证码:{}", capstr);
    }

}
